<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="对应的停车场ID" prop="scParkingLotId">
        <el-input v-model="queryParams.scParkingLotId" placeholder="请输入对应的停车场ID" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计费规则状态" prop="scIsActive">
        <el-select v-model="queryParams.scIsActive" placeholder="请选择计费规则状态" clearable>
          <el-option v-for="dict in dict.type.sc_is_active" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="基础金额(元)" prop="scBaseAmount">
        <el-input v-model="queryParams.scBaseAmount" placeholder="请输入基础金额" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['rules:allRules:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['rules:allRules:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['rules:allRules:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['rules:allRules:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="allRulesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计费规则ID" align="center" prop="scRuleId" />
      <el-table-column label="对应的停车场ID" align="center" prop="scParkingLotId" />
      <el-table-column label="免费停车时间(分钟)" align="center" prop="scFreeTime" />
      <el-table-column label="创建的时间" align="center" prop="scCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scCreateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" align="center" prop="scUpdateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scUpdateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计费规则状态" align="center" prop="scIsActive">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.scIsActive" :active-value="1" :inactive-value="0" active-text="启用"
            inactive-text="禁用" @change="updateRuleStatus(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="封顶金额(元)" align="center" prop="scCapAmount" />
      <el-table-column label="基础金额(元)" align="center" prop="scBaseAmount" />
      <el-table-column label="基础时间(小时)" align="center" prop="scBaseTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['rules:allRules:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['rules:allRules:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改所有收费规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="对应的停车场ID" prop="scParkingLotId">
          <el-input v-model="form.scParkingLotId" placeholder="请输入对应的停车场ID" />
        </el-form-item>
        <el-form-item label="免费停车时间(分钟)" prop="scFreeTime">
          <el-input v-model="form.scFreeTime" placeholder="请输入免费停车时间" />
        </el-form-item>
        <el-form-item label="计费规则状态" prop="scIsActive">
          <!-- 使用 v-bind 绑定布尔值 true -->
          <el-select v-model="form.scIsActive" :disabled="true" placeholder="新增规则默认状态为禁用">
            <el-option v-for="dict in dict.type.sc_is_active" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封顶金额(元)" prop="scCapAmount">
          <el-input v-model="form.scCapAmount" placeholder="请输入封顶金额" />
        </el-form-item>
        <el-form-item label="基础金额(元)" prop="scBaseAmount">
          <el-input v-model="form.scBaseAmount" placeholder="请输入基础金额" />
        </el-form-item>
        <el-form-item label="基础时间(小时)" prop="scBaseTime">
          <el-input v-model="form.scBaseTime" placeholder="请输入基础时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllRules, getAllRules, delAllRules, addAllRules, updateAllRules } from "@/api/rules/allRules";
import { get } from "sortablejs";

export default {
  name: "AllRules",
  dicts: ['sc_is_active'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 所有收费规则表格数据
      allRulesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scParkingLotId: null,
        scIsActive: null,
        scBaseAmount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scParkingLotId: [
          { required: true, message: "对应的停车场ID不能为空", trigger: "blur" }
        ],
        scFreeTime: [
          { required: true, message: "免费停车时间不能为空", trigger: "blur" }
        ],
        // scIsActive: [
        //   { required: true, message: "计费规则状态不能为空", trigger: "change" }
        // ],
        scCapAmount: [
          { required: true, message: "封顶金额不能为空", trigger: "blur" }
        ],
        scBaseAmount: [
          { required: true, message: "基础金额不能为空", trigger: "blur" }
        ],
        scBaseTime: [
          { required: true, message: "基础时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询所有收费规则列表 */
    getList() {
      this.loading = true;
      listAllRules(this.queryParams).then(response => {
        this.allRulesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scRuleId: null,
        scParkingLotId: null,
        scFreeTime: null,
        scCreateTime: null,
        scUpdateTime: null,
        scIsActive: null,
        scCapAmount: null,
        scBaseAmount: null,
        scBaseTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scRuleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加所有收费规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const scRuleId = row.scRuleId || this.ids
      getAllRules(scRuleId).then(response => {
        // 过滤掉时间字段
        const { scCreateTime, scUpdateTime, ...filteredData } = response.data;
        this.form = filteredData;
        this.open = true;
        this.title = "修改所有收费规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scRuleId != null) {
            updateAllRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAllRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 修改规则状态 */
    updateRuleStatus(row) {
      const formData = {
        scRuleId: row.scRuleId,
        scIsActive: row.scIsActive,
        scParkingLotId: row.scParkingLotId
      };
      // 检查是否已有启用规则
      if (formData.scIsActive === 1) {
        const params = {
          pageNum: 1,
          pageSize: 10,
          scParkingLotId: formData.scParkingLotId,
          scIsActive: 1
        };
        listAllRules(params).then(response => {
          if (response.rows && response.rows.length > 0) {
            this.$modal.msgError('该停车场已有启用规则，不能再启用新规则');
            row.scIsActive = !row.scIsActive;
            return;
          }
          // 没有启用规则，执行更新操作
          this.updateRule(formData);
          this.getList();
        });
      } else {
        // 直接执行更新操作
        this.updateRule(formData);
        this.getList();
      }
    },
    updateRule(formData) {
      updateAllRules(formData).then(response => {
        this.$modal.msgSuccess("状态更新成功");
      }).catch(error => {
        this.$modal.msgError("状态更新失败");
        // 恢复原来的状态
        const row = this.allRulesList.find(item => item.scRuleId === formData.scRuleId);
        if (row) {
          row.scIsActive = !row.scIsActive;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scRuleIds = row.scRuleId || this.ids;
      this.$modal.confirm('是否确认删除所有收费规则编号为"' + scRuleIds + '"的数据项？').then(function () {
        return delAllRules(scRuleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rules/allRules/export', {
        ...this.queryParams
      }, `allRules_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>